package com.ineatconseil.yougo.client.ui.main.application.tabs.requestsMngt;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.ineatconseil.yougo.client.cto.RequestCTO;
import com.ineatconseil.yougo.client.cto.RequestTypeCTO;
import com.ineatconseil.yougo.client.i18n.YougoLabelConstants;
import com.ineatconseil.yougo.client.ui.common.ClientFactory;
import com.ineatconseil.yougo.client.ui.common.popup.BasicPopup;

/**
 * @author Benjamin Barbier - Ineat Conseil
 */
public class RequestsActivity extends AbstractActivity implements IRequestsView.Presenter {

	private final ClientFactory clientFactory;
	private IRequestsView requestsView;
	private YougoLabelConstants constants;
	private RequestsPlace requestsPlace;
	
	public RequestsActivity(RequestsPlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
		requestsView = this.clientFactory.getRequestsView();
		requestsPlace = place;
	}
	
	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		System.out.println("RequestsActivity - start()");
		constants = clientFactory.getLabelConstants();
		getRequestTypes();
	}

	private void getRequestTypes() {
		clientFactory.getUserClientService().getRequestTypes(
				new AsyncCallback<JsArray<RequestTypeCTO>>() {
			@Override
			public void onFailure(Throwable caught) {
			}
			@Override
			public void onSuccess(JsArray<RequestTypeCTO> requestTypes) {
				requestsView.initTableColumns(requestTypes);
				getRequests();
			}
		});
	}
	
	private void getRequests() {
		clientFactory.getUserClientService().getRequests(
				requestsPlace.getUserId(), new AsyncCallback<JsArray<RequestCTO>>() {
			@Override
			public void onFailure(Throwable exception) {
				BasicPopup.showError(exception);
			}
			@Override
			public void onSuccess(final JsArray<RequestCTO> result) {
				requestsView.fillTable(Integer.parseInt(constants.pageSize()), result);
			}
		});
	}
	
	@Override
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);
	}

}
